package org.jiucheng.magpiebridge.client.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.MessageFormat;

import org.jiucheng.magpiebridge.util.Cfg;

public class ClientCfg {
    public static String getClientKey() {
        return Cfg.getProperty("client.key");
    }
    
    public static ServerInfo getServerInfo() {
        String opened = Cfg.getProperty("server.ipport.get.http.opened");
        if ("Y".equalsIgnoreCase(opened)) {
            String ipPort = doPostServerIpPort(MessageFormat.format("{0}/openapi/server/ip/port",
                    Cfg.getProperty("server.ipport.get.http.url")), getClientKey());
            if (ipPort == null || ipPort.length() == 0) {
                return null;
            }
            String[] strs = ipPort.split(":");
            return new ServerInfo(strs[0], Integer.valueOf(strs[1]));
        }
        return new ServerInfo(Cfg.getServerIp(), Cfg.getServerPort());
    }
    
    private static String doPostServerIpPort(String httpUrl, String clientKey) {
        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        String result = null;
        try {
            URL url = new URL(httpUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(20000);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            os = connection.getOutputStream();
            os.write(MessageFormat.format("clientToken={0}", URLEncoder.encode(clientKey, "UTF-8")).getBytes("UTF-8"));
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                if (sbf.length() > 0) {
                    result = sbf.substring(0, sbf.length() - 2);
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ConnectException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            connection.disconnect();
        }
        return result;
    }
}
